using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed;

    private Rigidbody2D _rb2D;
    private Animator _animator;

    private Vector2 _moveDirection = Vector2.left;
    private static readonly int IsWalk = Animator.StringToHash("IsWalk");
    private static readonly int MoveX = Animator.StringToHash("MoveX");
    private static readonly int MoveY = Animator.StringToHash("MoveY");

    private void Start()
    {
        _rb2D = GetComponent<Rigidbody2D>();
        _animator = GetComponent<Animator>();
    }

    private void Update()
    {
        ReadMovement();
    }

    private void FixedUpdate()
    {
        Move();
    }

    private void Move()
    {
        // 应用移动
        _rb2D.MovePosition(_rb2D.position + _moveDirection * (moveSpeed * Time.fixedDeltaTime));
    }

    private void ReadMovement()
    {
        // 获取玩家输入
        float moveX = Input.GetAxis("Horizontal");
        float moveY = Input.GetAxis("Vertical");

        // 移动方向
        _moveDirection = new Vector2(moveX, moveY).normalized;
        
        if (_moveDirection == Vector2.zero)
        {
            _animator.SetBool(IsWalk, false);
            return;
        }
        _animator.SetFloat(MoveX, _moveDirection.x);
        _animator.SetFloat(MoveY, _moveDirection.y );
       
        _animator.SetBool(IsWalk, true);
    }
}